package com.jzr.medical.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzr.common.entity.vo.Result;
import com.jzr.common.entity.vo.ResultPage;
import com.jzr.common.util.FileUtil;
import com.jzr.common.util.QueryUtil;
import com.jzr.common.util.U;
import com.jzr.medical.db1.dto.MediaDto;
import com.jzr.medical.db1.service.MediaService;
import com.jzr.medical.db1.vo.MediaVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/media")
public class MediaController {
    @Value("${file.media-upload-folder}")
    private String uploadFolder;

    @Value("${file.media-download-url}")
    private String downloadUrl;

    @Autowired
    private MediaService mediaService;

    @PostMapping("/list")
    public ResultPage<MediaVo> list(@RequestBody MediaDto record){
        QueryWrapper<MediaVo> qw = new QueryWrapper<>();
        QueryUtil.orderBy(qw,record.getOrderByClause());
        qw.eq(U.isNotBlank(record.getDeptCode()),MediaVo.DeptCode_,record.getDeptCode())
                .eq(U.isNotBlank(record.getFunType()),MediaVo.FunType_,record.getFunType())
                .likeRight(U.isNotBlank(record.getTitle()),MediaVo.Title_,record.getTitle());

        IPage<MediaVo> page = new Page<>(record.getPageNum(),record.getPageSize());
        List<MediaVo> list = mediaService.list(page,qw);
        page.setRecords(list);
        return ResultPage.success(page);
    }
    @PostMapping("/saveBatch")
    public Result<List<MediaVo>> saveBatch(@RequestBody List<MediaVo> list){
        List<MediaVo>  result = mediaService.saveBatch(list);
        return Result.success("成功",result);
    }

    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file, Integer id)  {
        if (file.isEmpty()) {
            return Result.fail("上传失败，请选择文件");
        }
        if(U.isBlank(id)){
            return Result.fail("上传失败，ID不能为空");
        }

        //用id做为文件名
        String fileName = id.toString() + "." + FileUtil.getExtension(file.getOriginalFilename());

        if(U.isBlank(uploadFolder)){
            return Result.fail("获取不了上传文件夹");
        }

        try {
            //删除旧文件
            deleteFile(id);

            File fullPath = new File(uploadFolder);
            if (!fullPath.exists()) {
                return Result.fail("上传文件夹不存在," + fullPath.getAbsolutePath());
            }

            File dest = new File(fullPath, fileName);
            if(dest.exists()){
                dest.delete();
            }
            file.transferTo(dest);
        }catch (IOException e){
            e.printStackTrace();
            return Result.fail("保存文件失败");
        }

        try {
            mediaService.updateFilename(id,fileName);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("保存记录失败");
        }

        return Result.success("保存成功",fileName);
    }

    @PostMapping("/saveContent")
    public Result<String> saveContent(String val, Integer id,String title)  {
        if (val.isEmpty()) {
            return Result.fail("上传失败，内容不能为空");
        }
        if(U.isBlank(id)){
            return Result.fail("上传失败，ID不能为空");
        }

        //用id做为文件名
        String fileName = id.toString() + ".html";

        if(U.isBlank(uploadFolder)){
            return Result.fail("获取不了上传文件夹");
        }

        try {
            //删除旧文件
            deleteFile(id);

            File fullPath = new File(uploadFolder);
            if (!fullPath.exists()) {
                return Result.fail("上传文件夹不存在," + fullPath.getAbsolutePath());
            }

            String templet = FileUtil.readAll(new File(uploadFolder,"templet.html"));
            if(U.isNotBlank(templet)) {
                templet = templet.replaceAll("\\$\\{title}", title);
                templet = templet.replaceAll("\\$\\{body}", val);
            }

            FileUtil.write(uploadFolder,fileName,templet==null ? val : templet);

        }catch (IOException e){
            e.printStackTrace();
            return Result.fail("保存文件失败");
        }

        try {
            mediaService.updateFilename(id,fileName);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("保存记录失败");
        }

        return Result.success("保存成功",fileName);
    }

    @GetMapping("/getContent")
    public Result<String> getContent(Integer id){
        if(id == null){
            return Result.fail("id不能为空");
        }
        String fileName = id.toString()+".html";
        String sb = "";
        try {
            File fullPath = new File(uploadFolder);
            if (!fullPath.exists()) {
                return Result.fail("文件夹不存在," + fullPath.getAbsolutePath());
            }

            File dest = new File(fullPath, fileName);
            if (dest.exists()) {
                sb = FileUtil.readAll(dest);
            }
        }catch (IOException e){
            e.printStackTrace();
            return Result.fail("保存文件失败");
        }
        int s = sb.indexOf("<body");
        if(s == -1){
            s = 0;
        }else{
            s = s + "<body".length();
            s = sb.indexOf(">",s);
            if(s == -1){
                s = 0;
            }else{
                s += 1;
            }
        }
        int e = sb.indexOf("</body>");
        if(e == -1){
            e = sb.length();
        }

        return Result.success("成功",sb.substring(s,e));
    }
//    @InitBinder
//    public void initBinder(WebDataBinder binder) {
//        //转换日期
//        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
//    }
    private void deleteFile(Integer id){
        String fileName = mediaService.getFileName(id);
        if(U.isNotBlank(fileName)){
            File dest = new File(uploadFolder,fileName);
            if(dest.exists()){
                dest.delete();
            }
        }
    }

}
